import React, { useEffect, useRef, useState } from "react";

import GamepadController from "../utils/GamepadController.js";

import '../index.css';

import demoImg from "../assets/demo1.jpg";

const Game = () => {
  const [config, setConfig] = useState({});
  const configId = 'game_1920x1280'
  const controllerRef = useRef(null);
  useEffect(() => {
    const controller = GamepadController.getInstance(controllerRef.current)
    console.log('controllerRef.current', controllerRef.current, controllerRef.current.clientHeight)
    controller.loadGameConfig(configId)
    controller.switchMode(1, gamepadHandler)
    controller.registerTouchEvent('down', (e) => { 
      console.log('touch down', e)
    })
    controller.registerTouchEvent('move', (e) => { 
      console.log('touch move', e)
    })
    controller.registerTouchEvent('up', (e) => { 
      console.log('touch up', e)
    })
  }, []);


  const gamepadHandler = e => {
    console.log('gamepadHandler', e)
    if(e.code != '200' ){
      return console.log('gamepad error', e.message)
    }
    if(e.eventType == 'connect'){
      onGamepadConnect(e)
    } else if(e.eventType == 'press'){
      onGamepadButtonPress(e)
    } else if(e.eventType == 'release'){
      onGamepadButtonRelease(e)
    } else if(e.eventType == 'move'){
      onGamepadAxisMove(e)
    }
  }

  const onGamepadConnect = (e) => {
    const { id } = e.gamepad;

    console.log(`${id} connected!`);
  };
  const onGamepadButtonPress = (e) => {
    console.log(`pressed!`, e);
  };

  const onGamepadButtonRelease = (e) => {
    console.log(`released!`, e);
    
  };

  const onGamepadAxisMove = (e) => {
    // const { axisName, value } = e.detail;
    console.log("onGamepadAxisMove", e);
    // console.log(gamepad2touchRef.current.state)
    // if(gamepad2touchRef.current.state > 0){
    //   gamepad2touchRef.current.eventAdapter(e)
    // }
    // console.log(`$e was moved to ${e}!`);
  };


  return <div className="w-4/5 bg-opacity-50 bg-gray-500 relative mx-auto">
      <img src={demoImg} alt="" />
      <div ref={controllerRef}  className="w-full h-full absolute top-0 left-0 bottom-0"></div>
    </div>
};

export default Game;

